package com.vito.oa.act.extend.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.vito.act.model.ActExProcessBranchModel;
import com.vito.act.model.ActSubProcessModel;
import com.vito.act.service.impl.ActExProcessBranchServiceImpl;
import com.vito.base.authoriza.dao.BaseSqlMapper;
import com.vito.base.authoriza.dao.SQLAdapterMapper;
import com.vito.base.authoriza.model.BaseSql;
import com.vito.base.model.DataGrid;
import com.vito.base.model.MyHashMap;
import com.vito.base.util.JSONUtil;
import com.vito.base.util.StringUtil;
import com.vito.base.util.Validata;
import com.vito.oa.act.constant.OaActContants;
import com.vito.oa.act.extend.dao.OaActExBussDefMapper;
import com.vito.oa.act.extend.dao.OaActExProcessBranchMapper;
import com.vito.oa.act.extend.model.OaActEExBussDefModel;
import com.vito.oa.act.extend.model.OaActExUserDefinedPro;
import com.vito.oa.act.extend.service.OaActExProcessBranchProService;

@Service
public class OaActExProcessBranchServiceImpl extends ActExProcessBranchServiceImpl implements OaActExProcessBranchProService{
	
	@Autowired
	private OaActExProcessBranchMapper oaProcessBranchMapper;
	@Autowired
	private OaActExBussDefMapper actExBussDefMapper;
	@Autowired
	private BaseSqlMapper baseSqlMapper ;
	@Autowired
	private SQLAdapterMapper sqlAdapterMapper;
	
	@Override
	public DataGrid<ActExProcessBranchModel> queryActExProcessBranchByPage(
			ActExProcessBranchModel processBranchModel) {
		DataGrid<ActExProcessBranchModel> dg = new DataGrid<ActExProcessBranchModel>();
		dg.setRows(oaProcessBranchMapper.queryActExProcessBranchByPage(processBranchModel));
		dg.setTotal(oaProcessBranchMapper.queryActExProcessBranchByPageCount(processBranchModel));
		return dg;
	}
	@Override
	public Map<String, Object> querySelectPage(Map<String, String> map) throws Exception {
		
		List<MyHashMap<String, String>>  list = actExBussDefMapper.queryBussNeedCols(map.get("processKey"), map.get("processNodeId"));
		
		Map<String,Object> mapCols = new HashMap<String,Object>();
		Iterator<MyHashMap<String, String>> listIt = list.iterator();
		while(listIt.hasNext()){
			MyHashMap<String, String> tempMap = listIt.next();
			if(!StringUtil.isEmpty(tempMap.get("dataid"))){	
				String dataid = tempMap.get("dataid");
				BaseSql baseSql = new BaseSql();
				if(dataid.length()>0&&dataid.indexOf("UC")==0){
					baseSql.setQueryId("actcode");
					baseSql = baseSqlMapper.queryBaseSqlById(baseSql);
					List<Map<?,?>> res =sqlAdapterMapper.getDataBysql(baseSql.getMapParam(new String[]{dataid}));
					mapCols.put(tempMap.get("colkey"), res);
				}else if(dataid.equalsIgnoreCase("basecode") || dataid.equalsIgnoreCase("baseTree")){
					baseSql.setQueryId(dataid);
					baseSql = baseSqlMapper.queryBaseSqlById(baseSql);
					List<Map<?,?>> res =sqlAdapterMapper.getDataBysql(baseSql.getMapParam(new String[]{tempMap.get("datasource")}));
					mapCols.put(tempMap.get("colkey"), res);
				}else{ // 新扩展的类型，例如link
					listIt.remove();
				}
			}
		}
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("item", list);
		resMap.put("detail", mapCols);
		return resMap;
	}
	@Override
	public void saveSubProcessSet(ActSubProcessModel aspm) {
		
		if(aspm.getDataonchange()!=null){
			Map<String,Object> maps = new HashMap<String,Object>();
			JSONArray json = new JSONArray(aspm.getDataonchange());
			List<Map<String,String>> para = new ArrayList<Map<String,String>>();
			for(int i=0 ; i < json.length() ;i++)  {
				 Map<String,String> data = new HashMap<String, String>();
				 JSONObject myjObject = json.getJSONObject(i);
				 data.put("text", myjObject.getString("text"));
				 data.put("id", myjObject.getString("id"));
				 para.add(data);
		    }
			maps.put("para", para);	
			maps.put("aspm", aspm);	
			oaProcessBranchMapper.saveSubProcessSetSelect(maps);
		}else{
			List<Map<String,Number>> para = new ArrayList<Map<String,Number>>();
			String[] str = aspm.getList();
			Map<String,Number> map = null;
			if(str!=null&&str.length>0){
				if(str.length>1){
					for(int i=0;i<str.length;i++){
						map= new HashMap<String,Number>();
						if(i==0){
							map.put("pre", Float.parseFloat(str[i]));
							map.put("status", 0);
						}else if(i==str.length-1){
							map.put("status", 1);
							map.put("suf",Float.parseFloat(str[i]));
							map.put("pre", Float.parseFloat(str[i-1]));
							para.add(map);
							map= new HashMap<String,Number>();
							map.put("status", -1);
							map.put("suf", Float.parseFloat(str[i]));
						}else{
							map.put("status", 1);
							map.put("suf", Float.parseFloat(str[i]));
							map.put("pre", Float.parseFloat(str[i-1]));
						}
						para.add(map);
						
					}
				}else{
					map= new HashMap<String,Number>();
					map.put("pre", Float.parseFloat(str[0]));
					para.add(map);
				}
				Map<String,Object> maps = new HashMap<String,Object>();
				maps.put("para", para);
				maps.put("aspm", aspm);
				oaProcessBranchMapper.saveSubProcessSet(maps);
			}
			
		}		
	}
	@Override
	public List<Map<String, Object>> querySubSet(Map<String, String> map) {
		return oaProcessBranchMapper.querySubSet(map);
	}
	@Override
	public Integer setDealUsers(OaActExUserDefinedPro userDefinedPro) {
		try{
			//1 删除上次设置数据
			String dfId = oaProcessBranchMapper.selectActExUserDefinedId(userDefinedPro);
			if(dfId!=null){
				userDefinedPro.setDefinedId(dfId);
				oaProcessBranchMapper.deleteActExUserDefined(userDefinedPro);
			}
			//2 重新插入最新设置的数据
			// 初始化参数
			String setUsers = userDefinedPro.getSetUserIds();
			if(!Validata.isNullOrEmpty(setUsers)){
				com.alibaba.fastjson.JSONArray array = JSONUtil.convertString2JsonArray(setUsers);
				if(array!=null&&array.size()>0){
					for (int i = 0; i < array.size(); i++) {
						userDefinedPro.setUserType(array.getJSONObject(i).getString("usertype"));
						if(i<(array.size()-1)){
							if(null != userDefinedPro.getUserId()){
								userDefinedPro.setUserId(userDefinedPro.getUserId()+array.getJSONObject(i).getString("userid")+OaActContants.SEPARATOR);
							}else{
								userDefinedPro.setUserId(array.getJSONObject(i).getString("userid")+OaActContants.SEPARATOR);
							}
							
						}else{
							if(null != userDefinedPro.getUserId()){
								userDefinedPro.setUserId(userDefinedPro.getUserId()+array.getJSONObject(i).getString("userid"));
							}else{
								userDefinedPro.setUserId(array.getJSONObject(i).getString("userid"));
							}
						}
					}
					oaProcessBranchMapper.saveActExUserDefined(userDefinedPro);
				}
			}
		}catch(Exception e){
			return -1;
		}
		return 1;
	}
	@Override
	public Integer updateActExProcessBranch(
			ActExProcessBranchModel processBranchModel) {
		try{
			if((processBranchModel.getStatus()).equals("-1")){
				//删除设置
				oaProcessBranchMapper.delActExProcessBranchModel(processBranchModel);
			}else{
				//启用或禁用设置
				oaProcessBranchMapper.updActExProcessBranchModel(processBranchModel);
			}
		}catch(Exception e){
			e.getMessage();
			return -1;
		}
		return 1;
	}
	@Override
	public DataGrid<OaActEExBussDefModel> queryActBussSubSetByPage(OaActEExBussDefModel actExBussDefModel) {
		List<OaActEExBussDefModel> listdata = oaProcessBranchMapper.queryActBussSubSetByPage(actExBussDefModel);
		if(null == listdata || listdata.isEmpty()){
			return null;
		}
		
		for(OaActEExBussDefModel defModel : listdata){
			if(defModel.getApprovalId() == null  || StringUtil.isEmpty(defModel.getApprovalId())){
				continue;
			}
			String userids[] = defModel.getApprovalId().split(OaActContants.SEPARATOR);
			List<Map<String,String>> userIdList = new ArrayList<Map<String,String>>();
			if(userids.length == 1){
				Map<String,String> userIdMap = new HashMap<String,String>();
				userIdMap.put("user_id", userids[0]);
				userIdMap.put("user_type", defModel.getApprovalTypeCode());
				userIdList.add(userIdMap);
			}
			else{
				for(String id :userids){
					Map<String,String> userIdMap = new HashMap<String,String>();
					userIdMap.put("user_id", id);
					userIdMap.put("user_type", "userid");
					userIdList.add(userIdMap);
				}
			}
			List<MyHashMap<String, String>> result = oaProcessBranchMapper.trUserInfo(userIdList);
			String useridStr = "";
			Iterator<MyHashMap<String, String>> it = result.iterator();
			while(it.hasNext()){
				MyHashMap<String, String> resultData = it.next();
				useridStr += resultData.get("username");
				useridStr += " ";
			}
			defModel.setApprovalId(useridStr);
		}
		DataGrid<OaActEExBussDefModel> dg = new DataGrid<OaActEExBussDefModel>();
		dg.setRows(listdata);
		dg.setTotal(listdata.size());
		return dg;
	}
	@Override
	public List<MyHashMap<String, String>> getUserImgs(OaActExUserDefinedPro userDefinedPro) {
		List<MyHashMap<String, String>> listData =  oaProcessBranchMapper.getUserImgs(userDefinedPro);
		if(listData!=null){
			List<MyHashMap<String, String>> newData = new ArrayList<MyHashMap<String, String>>();
			for(MyHashMap<String, String> data : listData){
				String userid = data.get("userid");
				if(null == userid ){
					continue;
				}
				if( userid.contains(OaActContants.SEPARATOR)){
					String userids[] = userid.split(OaActContants.SEPARATOR);
					List<Map<String,String>> userIdList = new ArrayList<Map<String,String>>();
					for(String id :userids){
						Map<String,String> userIdMap = new HashMap<String,String>();
						userIdMap.put("user_id", id);
						userIdMap.put("user_type", data.get("usertype"));
						userIdList.add(userIdMap);
					}
					List<MyHashMap<String, String>> result = oaProcessBranchMapper.trUserInfo(userIdList);
					if (null != result && !result.isEmpty())
						for (int i = 0; i < result.size(); i++) {
							MyHashMap<String, String> resultData = result.get(i);
							resultData.put("userid", userids[i]);
							resultData.put("usertype", data.get("usertype"));
							newData.add(resultData);
						}
				}else{
					newData.add(data);
				}
			}
			return newData;
		}
		return listData;
	}
	
	public static void main(String[] args) {
		System.out.println(Float.parseFloat("0.1"));
	}
	
	
	
}
